// 首页
import * as types from '@/store/mutation-types'
// import { isArray, isEmpty, hasIn } from 'lodash'
import api from '@/tools/api.js'
import { SUCCESS_STATUS } from '@/config/status'
import promise from '@/tools/promise'

const state = {
  list: {},
  all: [],
  detail: {}
}

// actions
const actions = {
  async getList ({ commit }, payload) {
    payload = {list_rows: 20, ...payload}
    let config = {loading: true, loadingText: '正在加载...'}
    let getRes = await api('serverauth/app/App/list', payload, config)
    SUCCESS_STATUS === getRes.status && commit(types.GET_APP_LIST, getRes.res)
  },
  async stop ({ commit }, payload) {
    let config = {loading: true, loadingText: '正在停止...'}
    let stopRes = await api('serverauth/app/App/stop', payload, config)
    return promise(stopRes)
  },
  async start ({ commit }, payload) {
    let config = {loading: true, loadingText: '正在启用...'}
    let startRes = await api('serverauth/app/App/start', payload, config)
    return promise(startRes)
  },
  async find ({ commit }, payload) {
    // let config = {loading: true, loadingText: '正在获取...'}
    let getRes = await api('serverauth/app/App/find', payload)
    SUCCESS_STATUS === getRes.status && commit(types.GET_APP_DETAIL, getRes.res)
  },
  // 为用户增加某些角色
  async addRoles ({ commit }, payload) {
    let config = {loading: true, loadingText: '正在增加...'}
    let addRes = await api('serverauth/app/App/addRoles', payload, config)
    return promise(addRes)
  },
  // 为用户移除某些角色
  async removeRoles ({ commit }, payload) {
    let config = {loading: true, loadingText: '正在移除...'}
    let removeRes = await api('serverauth/app/App/removeRoles', payload, config)
    return promise(removeRes)
  },
  // 编辑一个应用的名字
  async editAppName ({ commit }, payload) {
    payload = {id: payload.id, name: payload.name}
    let config = {loading: true, loadingText: '正在保存...'}
    let saveRes = await api('serverauth/app/App/edit', payload, config)
    return promise(saveRes)
  },
  // 查看所有应用(不分页)
  async appAll ({ commit }, payload) {
    let getRes = await api('serverauth/app/App/all')
    if (SUCCESS_STATUS === getRes.status) {
      commit(types.GET_APP_ALL, getRes.res)
    }
  },
  // 增加一个应用
  async addApp ({ commit }, payload) {
    let config = {loading: true, loadingText: '正在增加...'}
    let addRes = await api('serverauth/app/App/add', payload, config)
    return promise(addRes)
  }
}

// mutations
const mutations = {
  [types.GET_APP_LIST] (state, payload) {
    state.list = payload
  },
  [types.GET_APP_ALL] (state, payload) {
    state.all = payload
  },
  [types.GET_APP_DETAIL] (state, payload) {
    state.detail = payload
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
